package com.hisoka.common;

import com.hisoka.domain.MailAuth;
import com.hisoka.domain.MailInfo;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * MailSender.java
 * 
 * @author: Hinsteny
 * @date: 2017-03-20
 * @copyright: 2015 All rights reserved.
 * 
 */
public class MailSender {

    /**
     * 邮件发送
     * 
     * @param auth 发送邮件方的帐号信息
     * @param info 所要发送的邮件内容
     * @throws MessagingException
     */
    public static void send(final MailAuth auth, MailInfo info) throws MessagingException {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", auth.getMailHost());
        props.put("mail.debug", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(auth.getMailAcount(), auth.getMailPassword());
            }
        });

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(auth.getMailAcount()));
        String[] arr = info.getReceiver().split("，|,");
        InternetAddress[] address = new InternetAddress[arr.length];
        for (int i = 0; i < arr.length; i++) {
            address[i] = new InternetAddress(arr[i]);
        }
        msg.addRecipients(Message.RecipientType.TO, address);
        msg.setSubject(info.getSubject());
        msg.setSentDate(new Date());
        msg.setContent(info.getContent(), "text/html;charset=utf-8");
        Transport.send(msg);
    }

}
